// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using IBM.Data.DB2.Core;

namespace SnapObjects.Data.DB2 
{
    internal class DB2BoolTypeMapping : BoolTypeMapping
    {
        public DB2BoolTypeMapping([NotNull] string dbTypeName, [CanBeNull] DbType? dbType = null)
            : base(dbTypeName, System.Data.DbType.String)
        {
            this.ClrType = typeof(short);
        }

        public override Type ClrType { get; }

        protected override string GenerateNonNullSqlLiteral(object value)
        {
            if (value is short v && v > 0)
            {
                return "'t'";
            }

            if (value is bool b && b)
            {
                return "'t'";
            }

            return "'f'";
        }

        protected override void ConfigureParameter([NotNull] DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            if (parameter is DB2Parameter p)
            {
                var str = ValueConvert.ToString(p.Value);

                if (Int16.TryParse(str, out var v))
                {
                    p.Value = v > 0 ? 't' : 'f';
                }
            }
        }
    }
}
